#include "../../src/dm_karpov/heap_dmk.h"
#include <Windows.h>
#include "../../api/heap.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>

using namespace std;

void test( heap876 *hp )
{
	int *ptr[100000];
    int i;
	int j;
	int s=0;
	double deltaTime;
    static __int64 gTime,gLastTime;
	__int64 freq;
	printf("\n------------------------Test A Begin (Alloc one by one then free one by one)\n");
	printf("ALLOC BEGIN\n\n");
	QueryPerformanceCounter((LARGE_INTEGER *)&gLastTime);
    for (i=0; i < 10000; i++)
	{
		j = rand() % 2000;
		s += j;
		if (!(ptr[i]=(int *)hp->alloc(j)))
		{
		  printf("i = %d Error\n", i);
		  exit(-1);
		}
	}

	QueryPerformanceCounter((LARGE_INTEGER *)&gTime);
	QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
    deltaTime = (double)((double)(gTime - gLastTime)/(double)freq);
	printf("ALLOC FINISH :\n Amount of blocks = %d\n TIME = %f\n Amount of memory used = %d bytes\n\n", i, deltaTime, s);

	printf("Get occupancy = %d\n", hp->get_occupancy());

	printf("FREE BEGIN\n\n");
	QueryPerformanceCounter((LARGE_INTEGER *)&gLastTime);

    for (i=0; i < 10000; i++)
		hp->free((void *)ptr[i]);

	QueryPerformanceCounter((LARGE_INTEGER *)&gTime);
	QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
    deltaTime = (double)((double)(gTime - gLastTime)/(double)freq);
	printf("FREE FINISH :\nTIME = %f\n\n",  deltaTime);

	printf("Get occupancy = %d\n", hp->get_occupancy());

    printf("Test A OK\n");

	printf("\n------------------------Test B Begin (Alloc and  free in turn)\n");

	printf("ALLOC BEGIN\n\n");
	QueryPerformanceCounter((LARGE_INTEGER *)&gLastTime);
    for (i=0; i < 10000; i++)
	{
		j = rand() % 20;
		s += j;
		if (i % 2 == 1)
			hp->free((void *)ptr[i-1]);
		if (!(ptr[i]=(int *)hp->alloc(j)))
		{
		  printf("i = %d Alloc = 0 Error\n", i);
		  exit(-1);
		}
	}

	QueryPerformanceCounter((LARGE_INTEGER *)&gTime);
	QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
    deltaTime = (double)((double)(gTime - gLastTime)/(double)freq);
	printf("ALLOC FINISH :\n Amount of blocks = %d\n TIME = %f\n Amount of memory used = %d bytes\n\n", i, deltaTime, s);

	printf("Get occupancy = %d\n", hp->get_occupancy());

	printf("FREE BEGIN\n\n");
	QueryPerformanceCounter((LARGE_INTEGER *)&gLastTime);

	hp -> free_all(1);

	QueryPerformanceCounter((LARGE_INTEGER *)&gTime);
	QueryPerformanceFrequency((LARGE_INTEGER *)&freq);
    deltaTime = (double)((double)(gTime - gLastTime)/(double)freq);
	printf("FREE FINISH :\nTIME = %f\n\n",  deltaTime);

	printf("Get occupancy = %d\n", hp->get_occupancy());

    printf("Test B OK\n");

    exit(0);
}

int main () {
	heap_dmk hp(1024*1024*10, heap876::alloc_tagged);
	test(&hp);
	return 0;
}